/**
 * Copyright (c) 2010 sonntagsfarben.de
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

package de.sonntagsfarben.collections
{
	public class HashMapIterator implements IIterator
	{
		
		private var _index : uint = 0;
		private var _map : HashMap;
		private var _loop : Boolean;
		
		//TODO somehow an update is needed if the hashmap changes
		private var _array:Array;
		
		
		public function HashMapIterator(map:HashMap, loop:Boolean = false)
		{
			_map = map;
			_loop = loop;
			_array = _map.keys;
		}
		
		public function get index() : uint
		{
			return _index;
		}
		
		
		public function get nextIndex() : uint
		{
			return _index+1;
		}
		
		
		public function get previousIndex() : uint
		{
			return _index-1;
		}
		
		public function set index(index:uint):void
		{
			_index = index;
		}
		
		public function get current():*
		{
			if ( _array.length )
				return _map.getValue(_array[_index]);
			return null;
		}
		
		public function hasNext():Boolean
		{
			return ( _index < _array.length - 1 );
		}
		
		public function hasPrevious():Boolean
		{
			return ( _index > 0 );
		}
		
		public function next():*
		{
			if ( hasNext())
			{
				_index++;
				return _map.getValue(_array[_index]);
			}
			else 
			{
				if(_loop)
				{
					_index = 0;
					return _map.getValue(_array[_index]);
				}
				return null;
			}
		}
		
		public function previous():*
		{
			if ( hasPrevious() )
			{
				_index--;
				return _map.getValue(_array[_index]);
			}
			else
			{
				if(_loop)
				{
					_index = _array.length - 1;
					return _map.getValue(_array[_index]);
				}
				return null;
			}
		}
		
		public function reset():void
		{
			_index = 0;
		}
		
		public function get loop():Boolean
		{
			return _loop;
		}
		
		public function set loop(value:Boolean):void
		{
			_loop = value;
		}
	}
}